<?php
namespace App\Domain;

use App\Model\Order as ModelOrder;
use App\Model\Member as ModelMember;
use App\Model\Goods as ModelGoods;
use App\Model\Area as ModelArea;

class Order {

    //获取我的普通订单列表
    public function getOrderList( $user_id, $curpage, $where ) {
        $model = new ModelOrder();
        $all_data = array();
        //获取总数量，分页使用
        $count = $model->getOrderListCount( $user_id, $where );
        if( $count[0]['all_num'] < ($curpage * 10) ){
            $all_data['hasmore'] = false;
        }else{
            $all_data['hasmore'] = true;
        }
        $curpage = ($curpage * 10) - 10;
        //获取订单列表
        $all_data['data'] = $model->getOrderList( $user_id, $curpage, $where );
        foreach ( $all_data['data'] as $k => &$v ){
            //根据订单列表获取商品信息
            $goods_info = $model->getOrderGoodsDetail( $v['order_id'] );
            foreach ( $goods_info as $kk => $vv ){
                $v['goods_info'][$kk]['goods_id'] = $vv['goods_id'];
                $v['goods_info'][$kk]['goods_images'] = $vv['goods_images'];
                $v['goods_info'][$kk]['goods_name'] = $vv['goods_name'];
                $v['goods_info'][$kk]['spec_key'] = $vv['spec_key'];
                $v['goods_info'][$kk]['spec_key_name'] = $vv['spec_key_name'];
                $v['goods_info'][$kk]['goods_price'] = $vv['goods_price'];
                $v['goods_info'][$kk]['goods_num'] = $vv['goods_num'];
                $v['goods_info'][$kk]['prom_type'] = $vv['prom_type'];
                $v['goods_info'][$kk]['add_time'] = $vv['add_time'];
            }
        }
        return $all_data;
    }

    //订单详情
    public function getOrderDetail( $user_id, $order_id ) {
        $model = new ModelOrder();
        $data = array();
        //订单详情
        $data = $model->getOrderDetail( $user_id, $order_id );
        if( $data ){
            //地址信息
            $model_area = new ModelArea();
            $province = $model_area->getAreaInfo( $data['province'] );
            $city = $model_area->getAreaInfo( $data['city'] );
            $district = $model_area->getAreaInfo( $data['district'] );
            $data['province_name'] = $province['name'];
            $data['city_name'] = $city['name'];
            $data['district_name'] = $district['name'];
            $data['shipping_name'] = '';//快递公司
            $data['invoice_no'] = '';//快递单号
            //商品详情
            $goods_info = $model->getOrderGoodsDetail( $order_id );
            $data['goods_info'] = $goods_info;
            //快递详情
            if( $goods_info[0]['delivery_id'] ){
                $delivery_info = $model->getOrderGoodsDelivery( $goods_info[0]['delivery_id'] );
                $data['shipping_name'] = $delivery_info['shipping_name'];//快递公司
                $data['invoice_no'] = $delivery_info['invoice_no'];//快递单号
                //发起get请求
                $url = "https://m.kuaidi100.com/query?type=".$delivery_info['shipping_code']."&postid=".$delivery_info['invoice_no']."&id=1&valicode=&temp=0.49738534969422676";
                $res = $this->httpRequest( $url, 'get' );
                $data['delivery_status'] = $res['state'];
                $data['delivery_info'] = $res['data'];
            }else{
                $data['delivery_info'] = '暂无信息';
            }
        }
        return $data;
    }

    //获取我参与的拼团列表
    public function getMyAssembleOrder( $user_id, $curpage ) {
        $model = new ModelOrder();
        $all_data = array();
        //获取总数量，分页使用
        $count = $model->getMyAssembleOrderCount( $user_id );
        if( $count[0]['all_num'] < ($curpage * 10) ){
            $all_data['hasmore'] = false;
        }else{
            $all_data['hasmore'] = true;
        }
        $curpage = ($curpage * 10) - 10;
        $all_data['data'] = $model->getMyAssembleOrder( $user_id, $curpage );
        return $all_data;
    }

    //订单退款
    public function returnOrder( $order_id ) {
        $model = new ModelOrder();
        $data = array();
        //订单退款
        return $model->returnOrder( $order_id );
    }



    //物流查询
    public function deliveryOrder( $order_id ) {
        $model = new ModelOrder();
        $goods_info = $model->getOrderGoodsDetail( $order_id );
        //快递详情
        if( $goods_info[0]['delivery_id'] ){
            $delivery_info = $model->getOrderGoodsDelivery( $goods_info[0]['delivery_id'] );
            //发起get请求
            $url = "https://m.kuaidi100.com/query?type=".$delivery_info['shipping_code']."&postid=".$delivery_info['invoice_no']."&id=1&valicode=&temp=0.49738534969422676";
            $res = $this->httpRequest( $url, 'get'  );
            $data = $res['data'];
        }else{
            $data = array();
        }
            return $data;
    }

    private function httpRequest( $url, $type, $data = array() ){
        $curl = new \PhalApi\CUrl();
        if( $type == 'get' ){
            $res = $curl->get( $url, 3000 );
            $res = json_decode( $res, true );
        }
        if( $type == 'post' ){
            $res = $curl->post( $url, $data,3000 );
            $res = json_decode( $res, true );
        }
        return $res;
    }

    //订单评论
    public function comment( $data ){
        $model = new ModelOrder();
//        if ( $data['img'] ){
//            $data['img'] = explode( ',', $data['img'] );
//        }
        //根据user_Id获取用户头像
        $model_member = new ModelMember();
        $memebr_info = $model_member->getUserPic( $data['user_id'] );
        $data['username'] = $memebr_info['nickname'];
        $data['head_pic'] = $memebr_info['head_pic'];
        $data['add_time'] = time();
        return $model->comment( $data );
    }

    //存储订单
    public function saveOrder( $openid, $user_id, $address_id, $price, $found_id, $cart, $goods, $order_sn, $prepay_id, $user_note='' ){
        $model = new ModelOrder();
        $goods_model = new ModelGoods();
        $info = json_decode($goods,true);
//        echo '<pre>';
//        var_dump($info);die;
        $data = array();
        $goods_info = array();
        $id = '';
//        $order_sn = $this->createOrder();
        foreach ( $info as $k => $v ){
            $admin_id = $v['admin_id'];
            $data['user_id'] = $user_id;
            //创建订单编号
            if( $k == 0 ){
                $data['order_sn'] = $order_sn;
            }else{
                $data['order_sn'] = $this->createOrder();
            }
            $data['total_amount'] = $price;
            foreach ( $v['value'] as $kk => $vv ){
                $goods_info[$kk]['goods_id'] = $vv['goods_id'];
                //查询goods_Info是否过期或者已下架
                $goods_sale = $goods_model->getGoodsDetail($vv['goods_id']);
                if( $goods_sale['is_on_sale'] != 1 ){
                    return false;
                }
                //根据goods_id，spec_key 来减库存(规格表)
                $res = $model->changeSpecNum( $vv['goods_id'],$vv['spec_key'], $vv['goods_num'] );
                if( empty( $res ) ){
                    return false;
                }
                //根据goods_id，来减库存(规格表)
                $res = $model->changeGoodsNum( $vv['goods_id'], $vv['goods_num'] );
                if( empty( $res ) ){
                    return false;
                }
                $goods_info[$kk]['goods_name'] = $vv['goods_name'];
                $goods_info[$kk]['prom_type'] = $vv['prom_type'];
                $goods_info[$kk]['prom_id'] = $vv['prom_id'];
                $goods_info[$kk]['spec_key'] = $vv['spec_key'];
                $goods_info[$kk]['market_price'] = $vv['market_price'];
                $goods_info[$kk]['goods_price'] = $vv['goods_price'];
                $goods_info[$kk]['goods_num'] = $vv['goods_num'];
                $goods_info[$kk]['images'] = $vv['images'];
                $goods_info[$kk]['spec'] = $vv['spec'];
            }
            $data['goods_info'] = json_encode( $goods_info );
            $data['openid'] = $openid;
            $data['found_id'] = $found_id;//todo 当不为零时，需要修改found表，在follow表中添加数据（在支付完成后处理，记得哦~）
            $data['add_time'] = time();
            $data['is_success'] = 1;
            $data['is_cart'] = $cart;
            if(  $k == 0  ){
                $data['parent_ordersn'] = 0;
            }else{
                $data['parent_ordersn'] = $order_sn;
            }
            $data['admin_id'] = $admin_id;
            $data['address_id'] = $address_id;
            $data['user_note'] = $user_note;

            //处理prepay_id
            $prepay_data = array();
            $prepay_data = explode('=',$prepay_id);
            $data['form_id'] = $prepay_data[1];
            //插入临时表
            $id = $id.','.$model->saveOrder($data);
        }
        $id = ltrim( $id, ',' );
        return $order_sn;
    }

    //创建订单号
    public function createOrder(){
        $out_trade_no = date("YmdHis");
        $chars = '0123456789';
        $max = strlen($chars) - 1;
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        for ($i = 0; $i < 4; $i++) {
            $out_trade_no .= $chars[mt_rand(0, $max)];
        }
        return $out_trade_no;
    }

    //检测订单是否支付完成
    public function orderVerify( $order_sn ){
        $model = new ModelOrder();
        $data = $model->orderVerify( $order_sn );
        if( empty( $data ) ){
            //根据order_sn去中间表查询数据，还原库存即可
            $info = $model->orderTemporary( $order_sn );
            $goods_info = json_decode($info['goods_info'],true);
            foreach ( $goods_info as $k => $v ){
                //根据goods_id，spec_key 来加库存(规格表)
                $res = $model->changeSpecNum( $v['goods_id'],$v['spec_key'], $v['goods_num'], 2 );
                //根据goods_id，来加库存(规格表)
                $res = $model->changeGoodsNum( $v['goods_id'], $v['goods_num'], 2 );
            }
            //处理子订单
            $child_info = $model->orderTemporary( $order_sn, 2 );
            if( $child_info ){
                foreach ( $child_info as $k => $v ){
                    $child_goods_info = array();
                    $child_goods_info = json_decode($v['goods_info'],true);
                    foreach ( $child_goods_info as $kk => $vv ){
                        //根据goods_id，spec_key 来加库存(规格表)
                        $model->changeSpecNum( $vv['goods_id'],$vv['spec_key'], $vv['goods_num'], 2 );
                        //根据goods_id，来加库存(商品表)
                        $model->changeGoodsNum( $vv['goods_id'], $vv['goods_num'], 2 );
                    }
                }
            }
            return $data;
        }else{
            return $data;
        }
    }

    //订单各状态总和
    public function ordersStatus( $user_id ){
        $model = new ModelOrder();
        //根据user_Id获取用户头像
        $model_member = new ModelMember();
        $memebr_info = $model_member->ordersStatusById( $user_id );
        $data['username'] = $memebr_info['nickname'];
        $data['head_pic'] = $memebr_info['head_pic'];
        $data['add_time'] = time();
        return $model->comment( $data );
    }
}
